package com.coincalf.admin.web.funds.account;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.coincalf.admin.annotation.Log;
import com.coincalf.admin.common.ResultMap;
import com.coincalf.admin.entity.AccountDetail;
import com.coincalf.admin.enums.SysLogTypeEnum;
import com.coincalf.admin.service.AccountDetailService;
import com.coincalf.admin.view.ReportCsvUtils;
import com.google.common.base.Strings;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.supercsv.cellprocessor.CellProcessorAdaptor;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.util.CsvContext;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

/**
 * <p>
 * 资金账户流水 前端控制器
 * </p>
 *
 * @author Haliyo
 * @since 2018-05-16
 */
@RestController
@RequestMapping("/accountDetail")
@Api(value = "资金账户流水", description = "资金账户流水管理")
public class AccountDetailController {

    @Autowired
    private AccountDetailService accountDetailService;

    @Log(value = "按条件分页查询资金账户流水列表",type = SysLogTypeEnum.SELECT)
    @PreAuthorize("hasAuthority('account_detail_query')")
    @GetMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "每页显示条数，默认 10", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "accountId", value = "账户ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "coinId", value = "币种ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = " 用户ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注:充值(recharge_into) 提现审核通过(withdrawals_out) 下单(order_create) 成交(order_turnover) 成交手续费(order_turnover_poundage)  撤单(order_cancel)  注册奖励(bonus_register) 提币冻结解冻(withdrawals) 充人民币(recharge) 提币手续费(withdrawals_poundage)    兑换(cny_btcx_exchange) 奖励充值(bonus_into) 奖励冻结(bonus_freeze)", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "amountStart", value = "起始金额", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "amountEnd", value = "截止金额", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "String", paramType = "query"),
    })
    @ApiOperation(authorizations = {@Authorization(value="Authorization")},value = "按条件分页查询资金账户流水列表" ,httpMethod = "GET")
    public Object selectPage(@ApiIgnore Page<AccountDetail> page,
                             String accountId,String userId,
                             String coinId, String userName, String mobile,
                             String remark,String amountStart,String amountEnd,
                             String startTime,String endTime) {
        EntityWrapper<AccountDetail> ew = new EntityWrapper<>();
        if (!Strings.isNullOrEmpty(accountId)) {
            ew.eq("a.account_id", accountId);
        }
        if (!Strings.isNullOrEmpty(coinId)) {
            ew.eq("a.coin_id", coinId);
        }
        if (!Strings.isNullOrEmpty(userId)) {
            ew.eq("user_id", userId);
        }
        if(!Strings.isNullOrEmpty(mobile)){
            ew.like("b.mobile",mobile);
        }
        if(!Strings.isNullOrEmpty(remark)){
            ew.eq("a.business_type",remark);
        }
        if(!Strings.isNullOrEmpty(amountStart)){
            ew.ge("a.amount",amountStart);
        }
        if(!Strings.isNullOrEmpty(amountEnd)){
            ew.le("a.amount",amountEnd);
        }
        if (!Strings.isNullOrEmpty(userName)) {
            ew.where("b.username like '%"+userName+"%'");
        }
        if(!Strings.isNullOrEmpty(startTime)){
            ew.ge("a.created",startTime);
        }
        if(!Strings.isNullOrEmpty(endTime)){
            ew.le("a.created",endTime);
        }
        return ResultMap.getSuccessfulResult(accountDetailService.selectListPage(page, ew));
    }


    @Log(value = "导出资金账户流水",type = SysLogTypeEnum.EXPORT)
    @PreAuthorize("hasAuthority('account_detail_export')")
    @GetMapping
    @ApiOperation(authorizations = {@Authorization(value="Authorization")},value = "导出资金账户流水",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountId", value = "账户ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "coinId", value = "币种ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = " 用户ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注:充值(recharge_into) 提现审核通过(withdrawals_out) 下单(order_create) 成交(order_turnover) 成交手续费(order_turnover_poundage)  撤单(order_cancel)  注册奖励(bonus_register) 提币冻结解冻(withdrawals) 充人民币(recharge) 提币手续费(withdrawals_poundage)    兑换(cny_btcx_exchange) 奖励充值(bonus_into) 奖励冻结(bonus_freeze)", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "amountStart", value = "起始金额", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "amountEnd", value = "截止金额", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "String", paramType = "query"),
    })
    @RequestMapping({"/exportList"})
    public void export(@ApiIgnore Page<AccountDetail> page,
                               String accountId,String userId,
                               String coinId, String userName, String mobile,
                               String remark, String amountStart, String amountEnd,
                               String startTime, String endTime
                                    , HttpServletResponse response) throws Exception{
        EntityWrapper<AccountDetail> ew = new EntityWrapper<>();
        if (!Strings.isNullOrEmpty(accountId)) {
            ew.eq("a.account_id", accountId);
        }
        if (!Strings.isNullOrEmpty(coinId)) {
            ew.eq("a.coin_id", coinId);
        }
        if (!Strings.isNullOrEmpty(userId)) {
            ew.eq("a.user_id", userId);
        }
        if(!Strings.isNullOrEmpty(mobile)){
            ew.like("b.mobile",mobile);
        }
        if(!Strings.isNullOrEmpty(remark)){
            ew.eq("a.business_type",remark);
        }
        if(!Strings.isNullOrEmpty(amountStart)){
            ew.ge("a.amount",amountStart);
        }
        if(!Strings.isNullOrEmpty(amountEnd)){
            ew.le("a.amount",amountEnd);
        }
        if (!Strings.isNullOrEmpty(userName)) {
            ew.where("b.username like '%"+userName+"%'");
        }
        if(!Strings.isNullOrEmpty(startTime)){
            ew.ge("a.created",startTime);
        }
        if(!Strings.isNullOrEmpty(endTime)){
            ew.le("a.created",endTime);
        }
        page.setCurrent(1);
        page.setSize(100000);//限制导出数
        Page<AccountDetail> retPage = accountDetailService.selectListPage(page, ew);
        String[] header = {"ID", "账户ID", "关联账户ID", "用户名", "币种名称", "金额", "收付类型", "业务类型", "关联订单号", "发生时间", "备注"};
        String[] properties = {"idStr", "accountIdStr", "refAccountIdStr", "userName", "coinName", "amount", "directionStr", "businessTypeStr", "orderIdStr", "createdStr", "remark"};
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CellProcessor[] PROCESSORS = new CellProcessor[] {
                null,
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v ="\t"+String.valueOf(value);
                        return v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v ="\t"+String.valueOf(value);
                        return v;
                    }
                },
                null,
                null,
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v =String.valueOf(value);
                        if(value!=null){
                            DecimalFormat df=new DecimalFormat("0.00000000");
                            v=df.format(value);
                        }
                        return "\t"+v;
                    }
                },
                null,
                null,
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v ="\t"+String.valueOf(value);
                        return v;
                    }
                },
               null,
                null

        };

        String fileName="资金流水.csv";
        try {
            ReportCsvUtils.reportListCsv(response,header,properties,fileName, retPage.getRecords(),PROCESSORS);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

